<template>
  <div class="input-clear-wrap" :class="{w100: !size}">
    <input
      :class="warpClass"
      @change="$emit('change', currentValue)"
      ref="input"
      :placeholder="placeholder"
      :number="type === 'number'"
      :type="type"
      @focus="handleFocus($event)"
      @blur="handleBlur"
      :disabled="disabled"
      :readonly="readonly"
      :value="currentValue"
      @input="handleInput"
      :maxlength="maxlength"
    >
    <i
      class="zhk-sbylx"
      @click="handleClear"
      v-if="!disableClear"
      v-show="currentValue && type !== 'textarea' && active"
    ></i>
  </div>
</template>

<script>
export default {
  name: "inputClear",
  data() {
    return {
      active: false,
      currentValue: this.value,
      clickClear: false
    };
  },
  props: {
    size: {
      type: Boolean,
      default: false
    },
    type: {
      type: String,
      default: "text"
    },
    placeholder: String,
    max: Number,
    readonly: Boolean,
    disabled: Boolean,
    disableClear: Boolean,
    warpClass: {
      type: String,
      default: "default"
    },
    state: {
      type: String,
      default: "default"
    },
    value: {},
    attr: Object,
    maxlength: "",
    limitVal: {
      type: Function,
    },
  },
  mounted() {
    if(this.size) {
      this.$refs.input.size = String(this.currentValue||0).length+1;
    }
  },
  methods: {
    handleInput(evt) {
      let v = evt.target.value;
      if (this.limitVal) {
        v=this.limitVal(v);
      }
      if (this.max) {
        v = v.slice(0, this.max);
      }
      this.currentValue = v;
      this.max && this.$forceUpdate();
      this.limitVal && this.$forceUpdate();
    },
    handleClear() {
      if (this.disabled || this.readonly) return;
      this.currentValue = "";
      this.$nextTick(()=> {
        this.$refs.input.focus();
      })
    },
    handleFocus(e) {
      this.active = true;
      if (this.$listeners.focus) {
        this.$emit("focus", e);
      }
    },
    handleBlur() {
      setTimeout(() => {
        this.active = false;
      }, 300);
      if (this.$listeners.blur) {
        this.$emit("blur");
      }
    }
  },
  watch: {
    value(val, old) {
      this.currentValue = val;
      if(val) this.active = true;
    },
    currentValue(val) {
      if(this.size) {
        this.$refs.input.size = String(val||0).length+1;
      }
      this.$emit("input", val);
    },
    attr: {
      immediate: true,
      handler(attrs) {
        this.$nextTick(() => {
          const target = [this.$refs.input, this.$refs.textarea];
          target.forEach(el => {
            if (!el || !attrs) return;
            Object.keys(attrs).map(name => el.setAttribute(name, attrs[name]));
          });
        });
      }
    }
  }
};
</script>

<style lang='scss'>
@import "inputClear";
</style>